<template>
  <div class="admin-content-page">
    <div class="page-header">
      <h1>宣传视频管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchTitle"
          placeholder="请输入视频标题进行搜索"
          prefix-icon="Search"
          class="search-input"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;">
          搜索
        </el-button>
        <el-button @click="handleReset" style="margin-left: 10px;">
          重置
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedVideos.length === 0" style="margin-left: 10px;">
          <el-icon><CircleClose /></el-icon>
          批量删除
        </el-button>
        <el-button type="primary" @click="showUploadDialog">新增</el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="videoList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="title" label="标题" width="100"></el-table-column>
      <el-table-column prop="coverImage" label="封面图片" width="120">
        <template #default="scope">
          <!-- 如果视频有封面 -->
          <el-image v-if="scope.row.coverImage && scope.row.videoUrl" :src="scope.row.coverImage" :preview-src-list="[scope.row.coverImage]" class="video-cover"></el-image>
          <!-- 如果视频正在上传中（没有videoUrl但有taskId） -->
          <div v-else-if="scope.row.taskId" class="uploading-progress">
            <span class="uploading-text">上传中</span>
          </div>
          <!-- 其他情况 -->
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="videoUrl" label="视频" width="180">
          <template #default="scope">
            <el-button v-if="scope.row.videoUrl" type="primary" size="small" @click="playVideo(scope.row)">
              <el-icon><VideoPlay /></el-icon>
            </el-button>
            <!-- 上传中的视频显示上传进度 -->
            <div v-else-if="scope.row.taskId" class="uploading-progress">
              <span class="uploading-text">上传中</span>
            </div>
            <span v-else>无视频</span>
          </template>
        </el-table-column>
      <el-table-column prop="description" label="描述" width="250"></el-table-column>
      <el-table-column label="是否展示" width="250">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.isUse" 
            :active-value="1" 
            :inactive-value="0" 
            active-color="#13ce66" 
            inactive-color="#ff4949" 
            @change="handleIsUseChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="250" :formatter="formatDate"></el-table-column>
      <el-table-column label="操作" width="400" >
        <template #default="scope">
          <el-button type="primary" size="small" @click="showEditDialog(scope.row)" style="margin-right: 10px;">
            <el-icon><RefreshRight /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDeleteVideo(scope.row.id)">
            <el-icon><CircleClose /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 移除v-if条件，确保分页组件始终显示 -->
    <el-pagination
      class="pagination-container"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      layout="sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[5, 10, 20, 50]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 视频播放弹窗 -->
    <el-dialog v-model="videoDialogVisible" title="视频播放" width="80%" destroy-on-close>
      <video v-if="currentVideo" :src="currentVideo.videoUrl" controls class="video-player"></video>
    </el-dialog>

    <!-- 视频上传弹窗 -->
    <el-dialog v-model="uploadDialogVisible" title="新增宣传视频" width="600px" destroy-on-close>
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadFormRules" label-width="80px">
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="uploadForm.title" placeholder="请输入视频标题" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="视频描述" prop="description">
          <el-input v-model="uploadForm.description" type="textarea" placeholder="请输入视频描述（可选）" maxlength="200" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="视频文件" prop="videoFile">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleVideoFileChange"
            :show-file-list="true"
            :multiple="false"
            accept="video/*"
            action="#"
          >
            <el-button type="primary">选择视频文件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持 MP4、WebM、MOV 等视频格式，文件大小不超过100MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="封面图片">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleCoverFileChange"
            :show-file-list="true"
            :multiple="false"
            accept="image/*"
            action="#"
          >
            <el-button type="primary">选择封面图片</el-button>
            <template #tip>
              <div class="el-upload__tip">支持 JPG、PNG 等图片格式，文件大小不超过10MB（可选）</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAsyncUpload" :loading="loading">
            <el-icon v-if="loading"><Loading /></el-icon>
            <span>异步上传</span>
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 上传功能简化，移除进度弹窗 -->  
    
    <!-- 修改视频对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改视频信息"
      width="600px"
      :before-close="handleEditDialogClose"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入视频标题" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="视频描述" prop="description">
          <el-input v-model="editForm.description" placeholder="请输入视频描述" type="textarea" maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditDialogClose">取消</el-button>
          <el-button type="primary" @click="handleUpdateVideo" :loading="loading">
            <el-icon v-if="loading"><Loading /></el-icon>
            <span>保存修改</span>
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshRight, VideoPlay, Upload, Check, CircleClose, Clock, Loading } from '@element-plus/icons-vue'
import { findVideoPage, asyncUploadVideo, getUploadStatus, deleteVideo, batchDeleteVideos, updateVideoInfo ,isUse} from '@/api/video.js'

// 响应式数据
const videoList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchTitle = ref('')
const selectedVideos = ref([])
const videoDialogVisible = ref(false)
const currentVideo = ref(null)
// 上传状态轮询定时器
const pollingTimers = ref(new Map())

// 上传相关数据
const uploadDialogVisible = ref(false)
const uploadForm = ref({
  title: '',
  description: '',
  videoFile: null,
  coverFile: null
})
const uploadFormRules = ref({
  title: [
    { required: true, message: '请输入视频标题', trigger: 'blur' },
    { max: 50, message: '标题不能超过50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ],
  videoFile: [
    { required: true, message: '请选择视频文件', trigger: 'change' }
  ]
})
const uploadFormRef = ref(null)

// 修改视频相关数据
const editDialogVisible = ref(false)
const editForm = ref({
  id: '',
  title: '',
  description: ''
})
const editFormRules = ref({
  title: [
    { required: true, message: '请输入视频标题', trigger: 'blur' },
    { max: 50, message: '标题不能超过50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
})
const editFormRef = ref(null)

// 优化后的获取视频列表函数
const fetchVideoList = async (showLoading = true) => {
  if (showLoading) {
    loading.value = true
  }
  try {
    // 构建分页查询参数
    const pageDTO = {
      current: currentPage.value,
      size: pageSize.value,
      title: searchTitle.value || undefined
    }

    console.log('分页查询参数:', pageDTO)
    const response = await findVideoPage(pageDTO)
    console.log('API响应数据:', response)

    if (response.success) {
      let videos = Array.isArray(response.data) ? response.data : []

      videos = videos.map(video => ({
        ...video,
        isUse: typeof video.isUse === 'undefined' ?
            (typeof video.status === 'number' ? video.status : 0) :
            Number(video.isUse)
      }))

      videoList.value = videos
      
      // 优化total值设置逻辑，确保分页正确显示
      // 根据后端返回的数据结构，优先使用response.total字段
      if (response.total !== undefined && response.total !== null) {
        total.value = Number(response.total)
      }
      // 其次检查response.data是否有total字段（兼容不同的返回格式）
      else if (response.data && response.data.total !== undefined && response.data.total !== null) {
        total.value = Number(response.data.total)
      }
      // 最后，如果都没有，使用当前数据的数量作为默认值
      else {
        total.value = videos.length
      }
      
      console.log('最终设置的total值:', total.value)
    } else {
      ElMessage.error(response.message || '获取视频列表失败')
      // 即使请求失败，也设置一个默认的total值，确保分页组件可见
      total.value = 0
    }
  } catch (error) {
    console.error('获取视频列表失败:', error)
    ElMessage.error('获取视频列表失败')
    // 即使发生异常，也设置一个默认的total值，确保分页组件可见
    total.value = 0
  } finally {
    if (showLoading) {
      loading.value = false
    }
  }
}



// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchVideoList()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchVideoList()
}

// 选择视频处理
const handleSelectionChange = (selection) => {
  selectedVideos.value = selection
}

// 播放视频
const playVideo = (video) => {
  currentVideo.value = video
  videoDialogVisible.value = true
}

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) {
    return '--'
  }
  const date = new Date(cellValue)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 显示上传对话框
const showUploadDialog = () => {
  uploadForm.value = {
    title: '',
    description: '',
    videoFile: null,
    coverFile: null
  }
  uploadDialogVisible.value = true
}

// 处理视频文件选择
const handleVideoFileChange = (file, fileList) => {
  if (fileList.length > 0) {
    uploadForm.value.videoFile = fileList[0].raw
  } else {
    uploadForm.value.videoFile = null
  }
}

// 处理封面文件选择
const handleCoverFileChange = (file, fileList) => {
  if (fileList.length > 0) {
    uploadForm.value.coverFile = fileList[0].raw
  } else {
    uploadForm.value.coverFile = null
  }
}

// 异步上传视频
const handleAsyncUpload = async () => {
  try {
    await uploadFormRef.value.validate()
    
    const formData = new FormData()
    formData.append('title', uploadForm.value.title)
    formData.append('description', uploadForm.value.description || '')
    formData.append('videoFile', uploadForm.value.videoFile)
    if (uploadForm.value.coverFile) {
      formData.append('coverFile', uploadForm.value.coverFile)
    }
    
    // 关闭上传弹窗
    uploadDialogVisible.value = false
    
    // 显示绿色提示
    ElMessage.success('开始上传视频...请稍等片刻。上传完成后手动刷新即可查看视频')
    
    // 调用异步上传接口，不传递任何进度回调参数
    // 不设置loading=true，避免显示全局加载动画
    const response = await asyncUploadVideo(formData, null)
    
    if (response.success && response.data) {
      const taskId = response.data
      
      // 立即刷新列表以显示上传中的视频，但不显示加载动画
      await fetchVideoList(false)
      
      // 开始轮询上传进度
      startStatusPolling(taskId)
    } else {

    }
  } catch (error) {
    console.error('上传视频失败:', error)
    if (error.name === 'Error' && !error.message.includes('取消')) {
      ElMessage.error('上传视频失败')
    }
  }
}

// 开始轮询上传状态
const startStatusPolling = (taskId) => {
  // 清除可能存在的相同任务的轮询
  if (pollingTimers.value.has(taskId)) {
    clearInterval(pollingTimers.value.get(taskId))
  }
  
  // 设置轮询间隔为2秒
  const timer = setInterval(async () => {
    try {
      const response = await getUploadStatus(taskId)
      
      if (response.success && response.data) {
        const { status } = response.data
        
        // 如果上传完成
        if (status === 'SUCCESS') {
          ElMessage.success('视频上传完成！')
          
          // 清除轮询
          clearStatusPolling(taskId)
          
          // 刷新列表
          setTimeout(() => {
            fetchVideoList()
          }, 500)
        } 
        // 如果上传失败
        else if (status === 'FAILED') {
          ElMessage.error('视频上传失败，请重试')
          clearStatusPolling(taskId)
        }
      } else {
        console.error('获取上传状态失败:', response.message)
      }
    } catch (error) {
      console.error('轮询上传状态异常:', error)
    }
  }, 2000)
  
  pollingTimers.value.set(taskId, timer)
}

// 清除轮询
const clearStatusPolling = (taskId) => {
  if (pollingTimers.value.has(taskId)) {
    clearTimeout(pollingTimers.value.get(taskId))
    pollingTimers.value.delete(taskId)
  }
}

// 删除单个视频
const handleDeleteVideo = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该视频吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteVideo(id)
    if (response.success) {
      ElMessage.success('删除成功')
      fetchVideoList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除视频失败:', error)
      ElMessage.error('删除视频失败')
    }
  }
}

// 批量删除视频
const handleBatchDelete = async () => {
  if (selectedVideos.value.length === 0) {
    ElMessage.warning('请选择要删除的视频')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedVideos.value.length}个视频吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedVideos.value.map(video => video.id)
    const response = await batchDeleteVideos(ids)
    if (response.success) {
      ElMessage.success('批量删除成功')
      selectedVideos.value = []
      fetchVideoList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除视频失败:', error)
      ElMessage.error('批量删除视频失败')
    }
  }
}

// 显示编辑对话框
const showEditDialog = (video) => {
  editForm.value = {
    id: video.id,
    title: video.title,
    description: video.description
  }
  editDialogVisible.value = true
}

// 处理编辑对话框关闭
const handleEditDialogClose = () => {
  editDialogVisible.value = false
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

  // 处理视频展示状态切换
const handleIsUseChange = async (video) => {
  try {
    const response = await isUse({
      id: video.id,
      status: video.isUse
    })
    
    if (response.success) {
      ElMessage.success('状态更新成功')
      fetchVideoList(false) // 不显示加载动画，静默刷新
    } else {
      // 如果更新失败，恢复原来的状态
      video.isUse = video.isUse === 1 ? 0 : 1
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    // 如果请求异常，恢复原来的状态
    video.isUse = video.isUse === 1 ? 0 : 1
    console.error('更新视频状态失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 更新视频信息
const handleUpdateVideo = async () => {
  try {
    await editFormRef.value.validate()
    
    loading.value = true
    const response = await updateVideoInfo({
      id: editForm.value.id,
      title: editForm.value.title,
      description: editForm.value.description
    })
    
    if (response.success) {
      ElMessage.success('更新成功')
      editDialogVisible.value = false
      fetchVideoList()
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新视频信息失败:', error)
    if (error.name !== 'Error' || !error.message.includes('取消')) {
      ElMessage.error('更新视频信息失败')
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取视频列表
onMounted(() => {
  fetchVideoList()
})

// 组件卸载时清除所有轮询
onUnmounted(() => {
  pollingTimers.value.forEach(timer => {
    clearTimeout(timer)
  })
  pollingTimers.value.clear()
})

// 搜索功能
const handleSearch = () => {
  currentPage.value = 1 // 重置页码
  fetchVideoList()
}

// 重置搜索条件和分页
const handleReset = () => {
  searchTitle.value = ''
  currentPage.value = 1
  fetchVideoList()
}

</script>

<style scoped>
.admin-content-page {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.video-cover {
  width: 80px;
  height: 60px;
  object-fit: cover;
}

.pagination-container {
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.video-player {
  width: 100%;
  height: 450px;
  object-fit: contain;
}

.upload-demo .el-upload-list {
  max-height: 100px;
  overflow-y: auto;
}

/* 视频上传中状态样式 */
.uploading-progress {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.uploading-text {
  font-size: 12px;
  color: #409eff;
}
</style>